/****
	Copyright 2011 Taras Kulbachka

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

		http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
package com.atdevsoft.apps.abyss;


import java.util.UUID;

import bak.pcj.list.LongArrayList;

import android.preference.PreferenceManager;
//we will still use text.ClipboardManager since we target older platforms
import android.text.ClipboardManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.text.Html;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Transformation;


@SuppressWarnings("deprecation")
public class QuoteAdapter extends SimpleCursorAdapter {
	
	public class QuoteAnim extends Animation {
	    private int mTargetHeight;
	    private View mView;	    

	    public QuoteAnim(View view, int targetHeight) {	    	
	        mView = view;
	        mTargetHeight = targetHeight;	        
	    }

	    @Override
	    protected void applyTransformation(float interpolatedTime, Transformation t) {
	        int newHeight;
	        newHeight = (int)(mTargetHeight*interpolatedTime);	        
	        mView.getLayoutParams().height = newHeight;
	        mView.requestLayout();
	    }

	    @Override
	    public boolean willChangeBounds() {
	        return true;
	    }
	}	
	
    private static final int TYPE_QUOTE = 0;
    private static final int TYPE_NEXT = 1;
    private static final int TYPE_MAX_COUNT = TYPE_NEXT + 1;
	
    private Context mContext;
    private LayoutInflater mLi;
    private int mCount;
    private QuotesNavigator mNavigator;
    // we will store ids of quotes added to favorites for current cursor's selection 
    // view for quote can be reused and we don't know if quote has been already added to favorites only from database field
    // we could update cursor on every 'add to favs' operation but it will collapse all headers which looks ugly
    private LongArrayList mAddedToFavs;
    private SharedPreferences mPreferences;
    
    public boolean enableAll = false;

    public QuoteAdapter (Context context, int layout, Cursor c, String[] from, int[] to, QuotesNavigator navigator) {
        super(context, layout, c, from, to);
        mContext = context;        
        mLi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mCount = c.getCount();
        mNavigator = navigator;
        mAddedToFavs = new LongArrayList();
        mPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
    }
    
    @Override
    public int getItemViewType(int position) {
        return (position + 1 == mCount) && (mCount > QuotesNavigator.QUOTES_PER_PAGE) ? TYPE_NEXT : TYPE_QUOTE;
    }

    @Override
    public int getViewTypeCount() {
        return TYPE_MAX_COUNT;
    }
    
    private View createNewView(Context context, Cursor cursor) {
    	View view = null;		
		int type = getItemViewType(cursor.getPosition());
		boolean isWhite = mPreferences.getBoolean("prefs_white_scheme", false);;
		switch (type) {
			case TYPE_QUOTE:
				if (isWhite)
					view = mLi.inflate(R.layout.quote_white, null);
				else
					view = mLi.inflate(R.layout.quote, null);
				setView(view);
				
				final ViewGroup header = (ViewGroup)view.findViewById(R.id.ll_header);
				final ViewGroup body = (ViewGroup)view.findViewById(R.id.rl_body);
				((ImageButton)view.findViewById(R.id.btn_extra)).setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						if (header.getVisibility() != View.VISIBLE) {
							header.measure(0, 0);
							int finalHeight = header.getMeasuredHeight();				
							QuoteAnim anim = new QuoteAnim(header, finalHeight); 
							
							anim.setDuration(200); 
							header.setVisibility(View.VISIBLE);
							header.getLayoutParams().height = 0;			
							header.requestLayout();				
							
							header.startAnimation(anim);
						}
					}
				});
				
				final ImageButton btnFavs = (ImageButton)view.findViewById(R.id.btn_favs);
				btnFavs.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						TextView tvId = (TextView)header.findViewById(R.id.tv_id);		
						TextView tvTitle = (TextView)header.findViewById(R.id.tv_posted);
				        TextView tvQuote = (TextView)body.findViewById(R.id.tv_quote);				        
				        mAddedToFavs.add((Long)tvId.getTag());
						final String quoteSource = String.format(mContext.getString(R.string.favs_qs_abyssbest), tvId.getText());
				    	ContentValues values = new ContentValues();
				    	values.put(DatabaseHelper.QUOTES_QUOTE, tvQuote.getText().toString());
				    	values.put(DatabaseHelper.QUOTES_POSTED, quoteSource);    	
				    	DatabaseHelper.databaseInsert(DatabaseHelper.TABLE_NAME_FAVORITES, null, values);
				    	// stupid decision for getting source id for favs, should be changed to something better
				    	DatabaseHelper.execSQL("update " + DatabaseHelper.TABLE_NAME_FAVORITES + " set " + DatabaseHelper.QUOTES_SOURCE_ID + " = " +
				    			DatabaseHelper.QUOTES_ID + " where " + DatabaseHelper.QUOTES_SOURCE_ID + " is null");

				    	DatabaseHelper.execSQL("update " + mNavigator.getCurrentTableName() + " set " + DatabaseHelper.QUOTES_ADDED_TO_FAVS + 
				    			" = 1 where " +	DatabaseHelper.QUOTES_SOURCE_ID + " = " + tvId.getText().toString());
				    					    	
				    	mPreferences.edit().putInt("top-visible" + QuotesActivity.LAST_VISIBLE_SUFFIX_FAVORITES, 0).commit();
				    	
				    	Toast.makeText(mContext, R.string.added_to_favs, Toast.LENGTH_SHORT).show();		    	
				    	
				    	
				    	Intent i = new Intent(mContext, FavsNotifierService.class);
				        i.setAction(FavsNotifierService.ACTION_SEND_QUOTE);
				        i.putExtra(FavsNotifierService.INTENT_EXTRA_QUOTE_SOURCE_ID, tvId.getText());
				        i.putExtra(FavsNotifierService.INTENT_EXTRA_QUOTE_EXTRA_TITLE, tvTitle.getText());
				        i.putExtra(FavsNotifierService.INTENT_EXTRA_QUOTE, tvQuote.getText());
				        
				        String deviceId = mPreferences.getString("app_install_id", "");
				        if (deviceId.equals("")) {
				        	deviceId = UUID.randomUUID().toString();
				        	mPreferences.edit().putString("app_install_id", deviceId).commit();
				        }
				        i.putExtra(FavsNotifierService.INTENT_EXTRA_SENDER, deviceId);
				        
				        mContext.startService(i);
				    	
				    	btnFavs.setEnabled(false);
					}
				});
				
				
				final ImageButton btnShare = (ImageButton)view.findViewById(R.id.btn_share);
				btnShare.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						TextView tvId = (TextView)header.findViewById(R.id.tv_id);		        
				        TextView tvQuote = (TextView)body.findViewById(R.id.tv_quote);
				        final String quoteSource = String.format(mContext.getString(R.string.favs_qs_abyssbest), tvId.getText());
				        
				        Intent sendTo = new Intent(Intent.ACTION_SEND);
						sendTo.setType("text/html");
						sendTo.putExtra(Intent.EXTRA_TEXT, quoteSource + "\n" + Html.fromHtml(tvQuote.getText().toString()).toString().trim());
						mContext.startActivity(Intent.createChooser(sendTo, mContext.getString(R.string.send_choose)));				
					}
				});
				
				final ImageButton btnCopy = (ImageButton)view.findViewById(R.id.btn_copy);
				btnCopy.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {						        
				        TextView tvQuote = (TextView)body.findViewById(R.id.tv_quote);
				        ClipboardManager clipboard = (ClipboardManager)mContext.getSystemService(Context.CLIPBOARD_SERVICE); 
						clipboard.setText(Html.fromHtml(tvQuote.getText().toString()).toString().trim());
						
						Toast.makeText(mContext, R.string.copied_to_clip, Toast.LENGTH_SHORT).show();
					}
				});		
				
				
				final ImageButton btnDelete = (ImageButton)view.findViewById(R.id.btn_delete);
				btnDelete.setOnClickListener(new View.OnClickListener() {					
					@Override
					public void onClick(View v) {
						final TextView tvId = (TextView)header.findViewById(R.id.tv_id);
						Dialog d = new AlertDialog.Builder(mContext)
		            	.setTitle(R.string.delete_quote)
		            	.setMessage(String.format(mContext.getString(R.string.delete_quote_confirm), tvId.getText()))
		            	.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
		            		public void onClick(DialogInterface dialog, int whichButton) {		            			
								DatabaseHelper.execSQL("delete from " + mNavigator.getCurrentTableName() + " where " + DatabaseHelper.QUOTES_ID + 
						    			" = " +	String.valueOf(tvId.getTag()));
								Intent i = new Intent(QuotesActivity.ACTION_NEED_REFRESH_DATA);
								i.putExtra(QuotesActivity.INTENT_EXTRA_REFRESH_TYPE, QuotesActivity.REFRESH_TYPE_FULL);
								mContext.sendBroadcast(i);
		            		}
		            	})
		            	.setNegativeButton(R.string.no, null)
		            	.create();		    	
						d.show();						
					}
				});	
				
				break;
			case TYPE_NEXT:
				if (isWhite)
					view = mLi.inflate(R.layout.next_page_white, null);
				else
					view = mLi.inflate(R.layout.next_page, null);				
				break;
		}		
		
    	return view;   	
    }

    private void setView(View v) {
    	((ViewGroup)v.findViewById(R.id.ll_header)).setVisibility(View.GONE);
    	Cursor c = getCursor();
    	
    	long id = c.getLong(c.getColumnIndex(DatabaseHelper.QUOTES_ID));
        String sourceId = c.getString(c.getColumnIndex(DatabaseHelper.QUOTES_SOURCE_ID));
        String posted = c.getString(c.getColumnIndex(DatabaseHelper.QUOTES_POSTED));
        String quote = c.getString(c.getColumnIndex(DatabaseHelper.QUOTES_QUOTE));   
        TextView tvId = (TextView)v.findViewById(R.id.tv_id);
        TextView tvPosted = (TextView)v.findViewById(R.id.tv_posted);
        TextView tvQuote = (TextView)v.findViewById(R.id.tv_quote);
        ImageButton btnFavs = (ImageButton)v.findViewById(R.id.btn_favs);
        
        tvId.setTag(Long.valueOf(id));
        
  		btnFavs.setEnabled((c.getInt(c.getColumnIndex(DatabaseHelper.QUOTES_ADDED_TO_FAVS)) == 0) && (!mAddedToFavs.contains(id)));
       
        tvId.setText(sourceId);
        tvPosted.setText(posted);      
        tvQuote.setText(Html.fromHtml(quote).toString().trim());  
    }
        
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
    	return createNewView(context, cursor);   
    }

    @Override
    public void bindView(View v, Context context, Cursor c) {
		int type = getItemViewType(c.getPosition());        
        if (v == null) {      
        	v = createNewView(context, c);
        } else {
        	if (type == TYPE_QUOTE)
        		setView(v);
        }        
    }
    
    @Override
    public void changeCursor(Cursor cursor) {
    	super.changeCursor(cursor);
    	mAddedToFavs.clear();
    	if (cursor != null) {
    		mCount = cursor.getCount();
    	} else {
    		mCount = 0;
    	}    	    		
    }
    
    @Override
    public boolean isEnabled(int position) { 
            return (enableAll) || ((position + 1 == mCount) && (mCount > QuotesNavigator.QUOTES_PER_PAGE)); 
    }     

}
